package com.nut.spp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.JsonNode;
import com.nut.spp.api.req.MemberCouponQueryReq;
import com.nut.spp.common.Constants;
import com.nut.spp.common.Result;
import com.nut.spp.entity.Member;
import com.nut.spp.entity.MemberCoupon;
import com.nut.spp.mapper.MemberCouponMapper;
import com.nut.spp.mapper.MemberMapper;
import com.nut.spp.redis.RedisKeys;
import com.nut.spp.redis.RedisLock;
import com.nut.spp.service.MemberCouponService;
import com.nut.spp.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MemberCouponServiceImpl implements MemberCouponService {

    @Autowired
    private MemberCouponMapper memberCouponMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private RedisLock redisLock;

    @Override
    public Result<IPage<MemberCoupon>> listPage(MemberCouponQueryReq req) {
        IPage<MemberCoupon> list = memberCouponMapper.listPage(req.newPage(), req.getMemberId(), req.getType(), req.getStatus());
        return Result.ok(list);
    }

    @Override
    public Result<MemberCoupon> getById(Integer id) {
        MemberCoupon memberCoupon = memberCouponMapper.selectById(id);
        return Result.ok(memberCoupon);
    }

    @Override
    public Result initCoupon(Long memberId, String mobile) {
        memberCouponMapper.updateMemberIdByMobile(mobile, memberId);
        return Result.ok();
    }

    @Override
    public Result sendCoupon(Integer id, Long sendMemberId, String receiveMobile) {

        Long memberId = null;
        Member member = memberMapper.selectByMobile(receiveMobile);
        if (member != null) {
            memberId = member.getId();
        }

        MemberCoupon coupon = memberCouponMapper.selectById(id);
        if (coupon == null) {
            return Result.fail("找不到代金券");
        }

        if (!coupon.getMemberId().equals(sendMemberId)) {
            return Result.fail("无权使用代金券");
        }
        if (coupon.getType().equals(1)) {
            return Result.fail("自用券不能赠送");
        }
        if (!coupon.getStatus().equals(0)) {
            return Result.fail("不能赠送");
        }

        //标记代金券已赠送
        MemberCoupon update = new MemberCoupon();
        update.setId(id);
        update.setStatus(4);
        memberCouponMapper.updateById(update);

        //赠送代金券
        MemberCoupon coupon1 = new MemberCoupon();
        coupon1.setMemberId(memberId);
        coupon1.setMobile(receiveMobile);
        coupon1.setMoney(coupon.getMoney());
        coupon1.setType(1);
        coupon1.setFromMemberId(sendMemberId);
        coupon1.setEndTime(coupon.getEndTime());
        coupon1.setStatus(0);
        memberCouponMapper.insert(coupon1);

        return Result.ok();
    }


    @Override
    public void callback(JsonNode jsonNode, String json) {

        try {

//        {
//            "data": [{
//            "orderNumber": "stringXXX",
//                    "phone": "15800000000",
//                    "payAmt": "100.00"
//        }],
//            "object": "coupon"
//        }

            Iterator<JsonNode> elements = jsonNode.get("data").elements();
            if (elements.hasNext()) {
                JsonNode next = elements.next();
                String orderNumber = next.get("orderNumber").asText();
                String phone = next.get("phone").asText();
                String payAmt = next.get("payAmt").asText();
                generateCoupon(orderNumber, payAmt, phone);
            }


        } catch (Exception e) {
            log.error("callback_error", e);
        }


    }

    @Override
    public void generateCoupon(String orderNo, String orderMoney, String mobile) {

        String redisKey = RedisKeys.getOrderKey(orderNo);
        Boolean isLock = redisLock.tryLock(redisKey, Constants.REQUEST_ID, 3, TimeUnit.SECONDS);
        if (!isLock) {
            log.info("get_redis_key_fail=," + redisKey);
            return;
        }

        Integer couponCount = memberCouponMapper.selectCountByOrderNo(orderNo);
        if (couponCount > 0) {
            log.info("coupon_generate_already,orderNo=" + orderNo);
            return;
        }

        Long memberId = null;
        Member member = memberMapper.selectByMobile(mobile);
        if (member != null) {
            memberId = member.getId();
        }

        //订单金额 元
        int money = new BigDecimal(orderMoney).intValue();

        //金额 元
//        Integer money = 1000;

        //生成自用券
        BigDecimal zyMoney = new BigDecimal(money).multiply(new BigDecimal(ZY_PERCENT)).divide(HUNDRED, RoundingMode.HALF_DOWN);

        String endTime = DateUtil.getYearPlus(1);

        //50 100 200 3000
        for (int[] aa : ZY_ARRAY) {

            int ff = zyMoney.multiply(new BigDecimal(aa[1])).divide(HUNDRED, RoundingMode.HALF_DOWN).intValue();
            int count = ff / aa[0];

            System.out.println(aa[0] + "=" + count);
            log.info("send_coupon_zy," + aa[0] + "=" + count);

            //转成分
            int couponMoney = aa[0] * 100;

            for (int i = 0; i < count; i++) {
                MemberCoupon memberCoupon = new MemberCoupon();
                memberCoupon.setMemberId(memberId);
                memberCoupon.setMobile(mobile);
                memberCoupon.setOrderNo(orderNo);
                memberCoupon.setMoney(couponMoney);
                memberCoupon.setType(1);
                memberCoupon.setStatus(0);
                memberCoupon.setEndTime(endTime);

                memberCouponMapper.insert(memberCoupon);
            }

        }

        //生成亲友券
        BigDecimal qyMoney = new BigDecimal(money).multiply(new BigDecimal(QY_PERCENT)).divide(HUNDRED, RoundingMode.HALF_DOWN);

        //50 100 200 3000
        for (int[] aa : QY_ARRAY) {

            int ff = qyMoney.multiply(new BigDecimal(aa[1])).divide(HUNDRED, RoundingMode.HALF_DOWN).intValue();
            int count = ff / aa[0];
            System.out.println(aa[0] + "=" + count);

            log.info("send_coupon_qy," + aa[0] + "=" + count);

            //转成分
            int couponMoney = aa[0] * 100;

            for (int i = 0; i < count; i++) {
                MemberCoupon memberCoupon = new MemberCoupon();
                memberCoupon.setMemberId(memberId);
                memberCoupon.setMobile(mobile);
                memberCoupon.setOrderNo(orderNo);
                memberCoupon.setMoney(couponMoney);
                memberCoupon.setType(2);
                memberCoupon.setStatus(0);
                memberCoupon.setEndTime(endTime);

                memberCouponMapper.insert(memberCoupon);
            }
        }

    }

    public static void main(String[] args) {

//        BigDecimal dd = new BigDecimal(250).multiply(new BigDecimal(25));
//
//        BigDecimal ff = dd.divide(HUNDRED);
//
//        int hh = ff.intValue() / 300;
//        System.out.println(hh);
//
//        BigDecimal gg = ff.divide(new BigDecimal(300), 1, BigDecimal.ROUND_HALF_UP);
//
//        System.out.println(gg.intValue());


        System.out.println(6 / 7);
        System.out.println(10 / 7);
        System.out.println(9 / 7);
        System.out.println(16 / 7);

        int money = new BigDecimal("3.25").intValue();
        System.out.println(money);

    }


}
